use axum::{
    extract::Query,
    routing::{get, post},
    Router,
};
use rust_decimal::Decimal;
use serde::Deserialize;

use crate::{
    error::AppErr,
    server::{req::device::DeviceInfo, Cbor},
    store::order::{self, TbOrder},
};

#[derive(Debug, Deserialize)]
struct CreateReq {
    cargo_col: u8,
    cargo_row: u8,
    product_id: u64,
    create_timestamp: u64,
    amount: Decimal,
    pay_method: String,
}

async fn on_create(info: DeviceInfo, req: Cbor<CreateReq>) -> Result<Cbor<u64>, AppErr> {
    let id = order::create(
        info.id,
        req.cargo_col,
        req.cargo_row,
        req.product_id,
        req.create_timestamp,
        req.amount,
        &req.pay_method,
    )
    .await?;
    Ok(Cbor(id))
}

#[derive(Debug, Deserialize)]
struct QueryReq {
    begin: u64,
    end: u64,
}

async fn on_query(info: DeviceInfo, req: Query<QueryReq>) -> Result<Cbor<Box<[TbOrder]>>, AppErr> {
    let orders = order::query_with_device(info.id, req.begin, req.end).await?;
    Ok(Cbor(orders))
}

pub fn register() -> Router {
    Router::new()
        .route("/create", post(on_create))
        .route("/query", get(on_query))
}
